<template>
	<view class="share-qrcode">
		<view class="qrcode-container">
			<view class="qrcode-wrapper">
				<canvas id="qrcode" canvas-id="qrcode" class="qrcode-canvas" />
			</view>
		</view>
		<canvas id="poster" canvas-id="poster" v-if="posterWidth&&posterHeight"
			:style="{'width':`${posterWidth}px`,'height':`${posterHeight}px`}" class="poster-canvas" />
		<g-button btn_text="保存到相册" :width="574" :height="100" :borderRadius="24" style="margin-top: 48rpx;"
			@click="clickBtn"></g-button>
	</view>
</template>

<script lang="ts" setup>
	import { onMounted, getCurrentInstance, Ref, ref, reactive, defineEmits } from 'vue';
	import REST_URL from '@/http/http.restUrl';
	import UQRCode from '@/uni_modules/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js';
	import { IPoster } from './types';
	import { GET_STORE_USERINFO } from '@/store/gettersType';
	import { useStore } from 'vuex';

	const store = useStore();

	const instance = getCurrentInstance();

	const emit = defineEmits(['openPotserSelector'])

	onMounted(async () => {
		drawQRCode();
		await uni.loginManger.$interceptor;
		getPosterList();
	})

	const ctx = uni.createCanvasContext('qrcode', instance);


	//二维码图片url
	const qrcodeImageUrl : Ref<string> = ref('');
	//未加工海报列表
	const posterList : Ref<IPoster[]> = ref([]);
	//已加工海报列表
	const completedPosterList : string[] = reactive([]);
	//海报宽
	const posterWidth : Ref<number> = ref(0);
	//海报长
	const posterHeight : Ref<number> = ref(0);

	const drawQRCode = () => {
		// 获取uQRCode实例
		const qr = new UQRCode();
		// 设置二维码内容
		qr.data = `${store.state.website}/pages_login/register/register?share_code=${store.state.userInfo.share_code}`;
		// 设置二维码大小，必须与canvas设置的宽高一致
		qr.size = uni.getWindowInfo().screenWidth * 336 / 750;
		// 调用制作二维码方法
		qr.make();
		// 设置uQRCode实例的canvas上下文
		qr.canvasContext = ctx;
		// 调用绘制方法将二维码图案绘制到canvas上
		qr.drawCanvas();
		//生成二维码图片
		uni.canvasToTempFilePath({
			canvasId: 'qrcode',
			success: (res) => { qrcodeImageUrl.value = res.tempFilePath }
		})
	}


	const getPosterList = async () => {
		const { data } = await uni.http.POST(REST_URL.getPosterList, {
			customer_id: store.getters[GET_STORE_USERINFO].id,
			versions: 2,
			redirect_url:`${store.state.website}/pages_login/register/register?share_code=${store.state.userInfo.share_code}`,
		})
		console.log(data);
		posterList.value = data.background;
		 // posterList.value = [...data.background,...data.background,...data.background]
		if (posterList.value[0]) {
			posterWidth.value = Number(posterList.value[0].poster_width);
			posterHeight.value = Number(posterList.value[0].poster_length);
		}
	}




	const clickBtn = async () => {
		if (!completedPosterList.length) {
			uni.showLoading({
				title: '正在生成分享海拔'
			})
			const list = await drawCompletePoster(posterList.value, qrcodeImageUrl.value);
			completedPosterList.push(...list);
			console.log('completedPosterList', completedPosterList);
			uni.hideLoading();
		}
		emit('openPotserSelector', completedPosterList);
	}



	//生成完整海报
	function drawCompletePoster(posterList : IPoster[], qrcodeImg : string) : Promise<string[]> {
		return new Promise(async (resolve, reject) => {
			const list : string[] = [];
			try {
				for (let i = 0; i < posterList.length; i++) {
					const posterItem = await drawPosterItem(posterList[i], qrcodeImg);
					list.push(posterItem)
				}
				resolve(list);
			} catch (e) {
				console.log(e)
				reject()
			}
		})
	}

	function drawPosterItem(poster : IPoster, qrcodeImg : string) : Promise<string> {
		return new Promise((resolve, reject) => {
			try {
				uni.getImageInfo({
					src: poster.images,
					success: async (res) => {
						const ctx = uni.createCanvasContext("poster");
						ctx.beginPath();
						ctx.fillStyle = '#ffffff';
						ctx.fillRect(0, 0, Number(poster.poster_width), Number(poster.poster_length));
						// #ifdef MP-WEIXIN
						ctx.drawImage(res.path, 0, 0, Number(poster.poster_width), Number(poster.poster_length));
						// #endif
						// #ifdef H5
						ctx.drawImage(await getBase64(poster.images), 0, 0, Number(poster.poster_width), Number(poster.poster_length));
						// #endif
						ctx.drawImage(qrcodeImg, Number(poster.x_location), Number(poster.y_location), Number(poster.qrcode_width), Number(poster.qrcode_length));
						ctx.closePath();

						ctx.draw(false, (e) => {
							uni.canvasToTempFilePath({
								canvasId: 'poster',
								success: (res) => {
									console.log(res);
									ctx.clearRect(0, 0, Number(poster.poster_width), Number(poster.poster_length));
									resolve(res.tempFilePath)
								},
								fail: () => {
									console.log('fail')
									reject()
								}
							});
						})
					},
					fail: () => {
						reject()
					}
				})
			} catch (e) {
			}

		})
	}

	const getBase64 = (imgUrl : string) : Promise<string> => {
		return new Promise((resolve, reject) => {
			let xhr = new XMLHttpRequest();
			const time = +new Date();
			xhr.open('get', imgUrl + `?time=${time}`, true);
			// 重点1
			xhr.responseType = 'blob';
			xhr.onload = function () {
				if (this.status == 200) {
					//得到一个blob对象
					let blob = this.response;
					// 重点2
					let oFileReader = new FileReader();
					oFileReader.onloadend = function (e) {
						// 结果
						const base64 : string = e.target.result
						resolve(base64);
					};
					oFileReader.readAsDataURL(blob);
				}
			};
			xhr.send();
		})
	}




	const save = () => {

		ctx.draw(true, (e) => {
			setTimeout(() => {
				uni.canvasToTempFilePath({
					canvasId: 'qrcode',
					success: (res) => {
						console.log(res)
						// #ifdef H5
						const aEle = document.createElement('a');
						aEle.download = '小律优创团队分享码';
						aEle.href = res.tempFilePath;
						document.body.appendChild(aEle);
						aEle.click();
						aEle.remove();
						// #endif	
						// #ifdef MP-WEIXIN
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.prompt.$showToast('保存成功')
							}
						})
						// #endif
					},
					fail: () => {
						console.log('fail')
					}
				}, instance);
			}, 300)
		})

	}
</script>

<style scoped lang="scss">
	@import "./shareQRCode.scss";
</style>